<script lang="ts" setup>
import type { DropMenu } from './typing';

import { computed } from 'vue';

import {
  Dropdown,
  Menu,
  MenuDivider,
  MenuItem,
  Popconfirm,
} from 'ant-design-vue';
import { isFunction, omit } from 'lodash-es';

import { Icon } from '#/components/icon';

defineOptions({
  name: 'Dropdown',
  inheritAttrs: false,
});
const props = withDefaults(defineProps<Props>(), {
  popConfirm: false,
  trigger: () => ['contextmenu'],
  dropMenuList: () => [],
  selectedKeys: () => [],
});

const emit = defineEmits<Emits>();

interface Emits {
  (e: 'menuEvent', value: DropMenu): void;
}

interface Props {
  popConfirm?: boolean;
  trigger?: ('click' | 'contextmenu' | 'hover')[];
  dropMenuList?: DropMenu[];
  selectedKeys?: string[];
}

function handleClickMenu(item: DropMenu) {
  const { event } = item;
  const menu = props.dropMenuList.find(
    (item) => `${item.event}` === `${event}`,
  );
  emit('menuEvent', menu as DropMenu);
  item.onClick?.();
}

const getPopConfirmAttrs = computed(() => {
  return (attrs: any) => {
    const originAttrs = omit(attrs, ['confirm', 'cancel', 'icon']);
    if (!attrs.onConfirm && attrs.confirm && isFunction(attrs.confirm))
      originAttrs.onConfirm = attrs.confirm;
    if (!attrs.onCancel && attrs.cancel && isFunction(attrs.cancel))
      originAttrs.onCancel = attrs.cancel;
    return originAttrs;
  };
});

const getAttr = (key: number | string) => ({ key });
</script>
<template>
  <Dropdown :trigger="trigger" v-bind="$attrs">
    <span>
      <slot></slot>
    </span>
    <template #overlay>
      <Menu :selected-keys="selectedKeys">
        <template v-for="item in dropMenuList" :key="`${item.event}`">
          <MenuItem
            v-bind="getAttr(item.event)"
            @click="handleClickMenu(item)"
            :disabled="item.disabled"
          >
            <Popconfirm
              v-if="popConfirm && item.popConfirm"
              v-bind="getPopConfirmAttrs(item.popConfirm)"
            >
              <template #icon v-if="item.popConfirm.icon">
                <Icon :icon="item.popConfirm.icon" />
              </template>
              <div>
                <Icon :icon="item.icon" v-if="item.icon" />
                <span class="ml-1">{{ item.text }}</span>
              </div>
            </Popconfirm>
            <template v-else>
              <Icon :icon="item.icon" v-if="item.icon" />
              <span class="ml-1">{{ item.text }}</span>
            </template>
          </MenuItem>
          <MenuDivider v-if="item.divider" :key="`d-${item.event}`" />
        </template>
      </Menu>
    </template>
  </Dropdown>
</template>
